package com.zyx.xunyilu.controller;

import com.zyx.xunyilu.config.jwt.JWTUtils;
import com.zyx.xunyilu.entity.User;
import com.zyx.xunyilu.service.UserService;
import com.zyx.xunyilu.utils.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @ClassName: QQLoginController
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/11/20 20:25
 */
@CrossOrigin
@RestController
@RequestMapping("/qq")
public class QQLoginController {

    @Autowired
    UserService userService;

    @Autowired
    JWTUtils jwtUtils;

    @PostMapping("/binding/exists")
    public RestResponse bindingExists(User user,
                                      @RequestParam("openId") String openId) {
        User user1 = userService.qqBindingExists(user, openId);
        User result = user1.clearUser();
        return RestResponse.ok(result);
    }

    @PostMapping("/binding/noexists")
    public RestResponse bindingNoExists(@Valid User user,
                                        @RequestParam("openId") String openId) {
        User user1 = userService.qqBindingNoExists(user, openId);
        return RestResponse.ok(user1.clearUser());
    }

    @PostMapping("/login")
    public RestResponse qqLogin(@RequestParam("openId") String openId) {
        User userByOpenId = userService.findUserByOpenId(openId);
        if (userByOpenId == null) {
            return RestResponse.fail("登录失败!");
        }
        String token = jwtUtils.sign(userByOpenId.getName(), userByOpenId.getPassword());
        userByOpenId.setToken(token);
        return RestResponse.ok(userByOpenId.clearUser());
    }

    @PostMapping("/check")
    public RestResponse check(String openId) {
        User userByOpenId = userService.findUserByOpenId(openId);
        if (userByOpenId == null) {
            return RestResponse.ok(false);
        }
        return RestResponse.ok(true);
    }

}
